//
//  SearchViewController.m
//  StationManager
//
//  Created by 泽华伟业 on 17/3/17.
//  Copyright © 2017年 Helong. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTopView.h"
#import "UserInfoModel.h"
#import "SearchMapViewController.h"
#import <BaiduMapKit/BaiduMapAPI_Search/BMKSuggestionSearch.h>
#import <BaiduMapKit/BaiduMapAPI_Search/BMKGeoCodeSearch.h>

@interface SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,BMKSuggestionSearchDelegate,BMKGeoCodeSearchDelegate>

//逆向地理编码
@property (nonatomic,strong) BMKGeoCodeSearch *searcherGeo;
//建议搜索
@property (nonatomic,strong) BMKSuggestionSearch *poisearch;
//城市名称
@property (nonatomic,copy) NSString *cityName;
//搜索记录列表
@property (nonatomic,strong) UITableView *recordTableView;
//搜索记录数组
@property (nonatomic,strong) NSMutableArray *recordArray;
//模糊搜索数组
@property (nonatomic,strong) NSArray *searchArray;
//模糊搜索列表
@property (nonatomic,strong) UITableView *fuzzySearchTableView;

@property (nonatomic,strong)UISearchBar *searchBar;

@end

@implementation SearchViewController

//视图将要显示
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _searcherGeo.delegate = self;
    _poisearch.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _searcherGeo.delegate = nil;
    _poisearch.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLOR(204, 204, 204);
    NSArray *searchAry = [USER_DEFAULT objectForKey:[self getUserId]];
    [self getCity];
    if (searchAry.count == 0) {
       _recordArray = [NSMutableArray array];
    }else{
       _recordArray = [NSMutableArray arrayWithArray:searchAry];
    }
    //模糊搜索数组
    _searchArray = [NSMutableArray array];
    //添加searchBar
    [self addSearchBarAndButton];
    [self addSearchTopViewAndTableView];
   }

- (void)getCity{

    //发起反向地理编码检索
    _searcherGeo = [[BMKGeoCodeSearch alloc]init];
    _searcherGeo.delegate = self;
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
    BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = _location;
    BOOL flag = [_searcherGeo reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
      NSLog(@"反geo检索发送成功");
    }
    else
    {
      NSLog(@"反geo检索发送失败");
    }
}
#pragma  mark -- 反向地理编码
//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
errorCode:(BMKSearchErrorCode)error{
  if (error == BMK_SEARCH_NO_ERROR) {
      _cityName = result.addressDetail.city;
  }
  else {
      NSLog(@"抱歉，未找到结果");
  }
}
- (void)addSearchBarAndButton{
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 160, 35)];
    _searchBar.tintColor = [UIColor clearColor];
    self.navigationItem.titleView = _searchBar;
    _searchBar.delegate = self;
}

//搜索列表懒加载
- (UITableView *)fuzzySearchTableView{
    if (!_fuzzySearchTableView) {
        _fuzzySearchTableView = [[UITableView alloc]initWithFrame:CGRectMake(150, 0, 200, 200) style:UITableViewStylePlain];
        [self.view addSubview:_fuzzySearchTableView];
        _fuzzySearchTableView.delegate = self;
        _fuzzySearchTableView.dataSource = self;
    }
    [_fuzzySearchTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_searchBar.mas_bottom);
        make.centerX.equalTo(_searchBar);
        make.width.equalTo(_searchBar).multipliedBy(0.7);
        make.height.mas_equalTo(30*hl*_searchArray.count);
    }];

    return _fuzzySearchTableView;
}

//添加常用搜索栏（美食，酒店，超市，加油站）
- (void)addSearchTopViewAndTableView{
    SearchTopView *topView = [[SearchTopView alloc]init];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(8*wl);
        make.right.equalTo(self.view).offset(-8*wl);
        make.top.equalTo(self.view).offset(10*hl);
        make.height.mas_equalTo(35*hl);
    }];
    //实现block把对应选项添加进数组并刷新列表
    topView.buttonTitleBlock = ^(NSString *buttonTitle){
        HLog(@"%@",buttonTitle);
        [self pushSearchMapControllerWithKeyWord:buttonTitle];
    };
    //添加历史记录列表
    _recordTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, 200, 200) style:UITableViewStylePlain];
    [self.view addSubview:_recordTableView];
    _recordTableView.delegate = self;
    _recordTableView.dataSource = self;
    [_recordTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(5*wl);
        make.right.equalTo(self.view.mas_right).offset(-5*wl);
        make.top.equalTo(topView.mas_bottom).offset(5*hl);
        make.height.mas_equalTo((_recordArray.count +1) *40*hl);
    }];
}

#pragma mark -- tabeleView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_recordTableView]) {
       return _recordArray.count;
    }else if ([tableView isEqual:_fuzzySearchTableView]){
        return _searchArray.count;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_recordTableView]) {
        return 40*hl;
    }else if ([tableView isEqual:_fuzzySearchTableView]){
        return 30*hl;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ([tableView isEqual:_recordTableView]) {
      return 40*hl;
    }else{
        return 0;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if ([tableView isEqual:_recordTableView]) {
        UIButton *deletaButton = [[UIButton alloc]init];
        if (_recordArray.count == 0) {
            [deletaButton setTitle:@"暂无历史记录" forState:UIControlStateNormal];
            deletaButton.userInteractionEnabled = NO;
        }else{
            [deletaButton setTitle:@"清空历史记录" forState:UIControlStateNormal];
            deletaButton.userInteractionEnabled = YES;
        }
        [deletaButton.titleLabel setFont:TEXT_FONT];
        [deletaButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [deletaButton addTarget:self action:@selector(deletaButtonDidSelected:) forControlEvents:UIControlEventTouchUpInside];
        return deletaButton;

    }else{
        return nil;
    }
}

#pragma mark -- 清空历史记录按钮点击
- (void)deletaButtonDidSelected:(UIButton *)sender{
    [_recordArray removeAllObjects];
    [_recordTableView reloadData];
    [_recordTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(5*wl);
        make.right.equalTo(self.view.mas_right).offset(-5*wl);
        make.top.equalTo(self.view).offset(50*hl);
        make.height.mas_equalTo((_recordArray.count +1) *40*hl);
    }];
    [USER_DEFAULT removeObjectForKey:[self getUserId]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_recordTableView]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchTabeleViewCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchTabeleViewCell"];
        }
        [cell.textLabel setText:[_recordArray objectAtIndex:indexPath.row]];
        return cell;
    }else if ([tableView isEqual:_fuzzySearchTableView]){
     ///如果是模糊搜索的列表
        UITableViewCell *searchCell = [tableView dequeueReusableCellWithIdentifier:@"fuzzySearchTableViewCell"];
        if (!searchCell) {
            searchCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"fuzzySearchTableView"];
        }
        [searchCell.textLabel setText:[_searchArray objectAtIndex:indexPath.row]];
        return searchCell;
    }
    return [[UITableViewCell alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_recordTableView]) {
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        //跳转并传递搜索关键词
        [self pushSearchMapControllerWithKeyWord:cell.textLabel.text];
    }else if ([tableView isEqual:_fuzzySearchTableView]){
        _searchBar.text = [_searchArray objectAtIndex:indexPath.row];
        //跳转并传递搜索关键词
        [self pushSearchMapControllerWithKeyWord:[_searchArray objectAtIndex:indexPath.row]];
    }
}

#pragma mark -- 跳转到searchMapConller的方法
- (void)pushSearchMapControllerWithKeyWord:(NSString *)keyWord{
    SearchMapViewController *searchMapVC = [[SearchMapViewController alloc]initWithKeyWord:keyWord];
    searchMapVC.location = _location;
    [self.navigationController pushViewController:searchMapVC animated:YES];
    //添加入数组 并刷新列表
    [self reloadDataAndChangeTableViewHeightWithString:keyWord];
}

#pragma mark -- searchBar代理方法
//输入文字改变时
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if ([searchText isEqualToString:@""]) {
        [self.fuzzySearchTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_searchBar.mas_bottom);
            make.centerX.equalTo(_searchBar);
            make.width.equalTo(_searchBar).multipliedBy(0.7);
            make.height.mas_equalTo(30*hl*0);
        }];
        return;
    }
    _poisearch = [[BMKSuggestionSearch alloc]init];
    _poisearch.delegate = self;
    BMKSuggestionSearchOption *suggestionOption = [[BMKSuggestionSearchOption alloc]init];
    suggestionOption.cityname= _cityName;
    suggestionOption.keyword = _searchBar.text;
    BOOL flag = [_poisearch suggestionSearch:suggestionOption];
    if(flag){
        NSLog(@"建议检索发送成功");
    }else{
        NSLog(@"建议检索发送失败");
    }
}
#pragma  mark -- 建议搜索代理方法
- (void)onGetSuggestionResult:(BMKSuggestionSearch *)searcher result:(BMKSuggestionResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
        HLog(@"%@",result.keyList);
        _searchArray = result.keyList;
        [self.fuzzySearchTableView reloadData];
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}
#pragma mark -- 点击搜索按钮 开始搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    HLog(@"%@",searchBar.text);
    [self pushSearchMapControllerWithKeyWord:searchBar.text];
}

//刷新tableview，改变其高度 ，并将数组重新存一遍
- (void)reloadDataAndChangeTableViewHeightWithString:(NSString *)searchString{
    int num = 0;
    for (NSString *str in _recordArray) {
        if ([str isEqualToString:searchString]) {
            num ++;
        }
    }
    if (num == 0) {
        [_recordArray insertObject:searchString atIndex:0];
    }
    [_recordTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(5*wl);
        make.right.equalTo(self.view.mas_right).offset(-5*wl);
        make.top.equalTo(self.view).offset(50*hl);
        make.height.mas_equalTo((_recordArray.count +1) *40*hl);
    }];
    [_recordTableView reloadData];
    [USER_DEFAULT setObject:_recordArray forKey:[self getUserId]];
}

- (NSString *)getUserId{
  NSData *data =  [USER_DEFAULT objectForKey:@"userInfoModel"];
    UserInfoModel *userInfModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return userInfModel.UserID;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often w  ant to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
